<template>
  <div style="margin: 10px">
    <h3 >单据详情</h3>
    <el-table
      v-if="isShowTable"
      :ref="'table1'+typeName"
      v-loading="loading"
      height="400px"
      :data="list"
      size="small"
      style="width: 100%;"
      :show-summary="true"
      sortable="custom"
      border
      :row-style="rowClass"
      highlight-current-row="highlight-current-row"
      :row-class-name="tableRowClassName"
      @row-click="selectRow"
      @header-dragend="changeColWidth"
      @row-dblclick="switchRowIndex"
      @selection-change="selectionChangeHandler"
    >
      <el-table-column type="selection" width="60" />
      <el-table-column type="index" width="60" label="序号" />
      <el-table-column v-for="(item,index) in header" v-if="item.visible" :label="columnLabel(item)" :prop="item.prop" :width="item.width">
        <template slot-scope="scope">
          <!-- 当列key为 sort 时，渲染一个手柄icon -->
          <template v-if="item.prop =='sort'">
            <div class="handle_move">
              <i :class="scope.row['sort']" />
            </div>
          </template>
          <template v-else>
            <span v-if="item.type == 1">
              {{ scope.row[`${item.prop}`] }}
            </span>
            <span v-else-if="item.type == 2">{{ parseTime(scope.row[`${item.prop}`]) }}</span>
            <span v-else-if="item.type == 3">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
            <span v-else-if="item.type == 4">
              <span v-if="item.prop == 'goodsName'" style="display: flex;align-items: center">
                <span v-if="scope.$index !== rowIndex">{{ scope.row.goodsName }}</span>
                <el-input v-else v-model="scope.row.goodsName" placeholder="请输入商品" />
              </span>
              <span v-else-if="item.prop == 'discountRate'">
                <span v-if="scope.$index !== rowIndex">{{ scope.row.discountRate }}%</span>
                <el-input
                  v-if="scope.$index === rowIndex"
                  v-model.lazy="scope.row.discountRate"
                  oninput="value=value.replace(/[^\d^\.]/g,'')"
                  maxlength="12"
                  style="width: 100%"
                  @input.native="inuptCount(scope, 'discountRate')"
                >
                  <template slot="append">
                    %
                  </template>
                </el-input>
              </span>
              <span v-else-if="item.prop == 'taxPrice'" style="display: flex;justify-content: center;align-items: center">

                <span v-if="scope.$index !== rowIndex">{{ scope.row.taxPrice }}</span>
                <el-input
                  v-else
                  v-model="scope.row.taxPrice"
                  oninput="value=value.replace(/[^\d^\.]/g,'')"
                  maxlength="12"
                  placeholder="请输入内容"
                  @input="inuptCount(scope, 'taxPrice')"
                />
              </span>
              <span v-else-if="item.prop == 'taxBoxPrice'" style="display: flex;justify-content: center;align-items: center">
                <span v-if="scope.$index !== rowIndex">{{ scope.row.taxBoxPrice }}</span>
                <el-input
                  v-else
                  v-model="scope.row.taxBoxPrice"
                  oninput="value=value.replace(/[^\d^\.]/g,'')"
                  maxlength="12"
                  placeholder="请输入内容"
                  @input.native="inuptCount(scope, 'taxBoxPrice')"
                />
              </span>
              <span v-else-if="item.prop == 'goodsCount'">
                <span v-if="scope.$index !== rowIndex">{{ scope.row.goodsCount }}</span>
                <el-input
                  v-else
                  v-model="scope.row.goodsCount"
                  placeholder="请输入内容"
                  @input="computedMoney(scope.row)"
                />
              </span>
              <span v-else-if="item.prop == 'boxNum'">
                <span v-if="scope.$index !== rowIndex ">{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
                <el-input
                  v-else
                  v-model="scope.row.boxNum"
                  maxlength="12"
                  style="width:49%;float: left"
                  @input.native="inuptCount(scope, 'boxNum')"
                >
                  <template slot="append">{{ scope.row.boxUnitName }}</template>
                </el-input>
                <span v-if="scope.$index !== rowIndex">{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
                <el-input
                  v-else
                  v-model="scope.row.mainNum"
                  maxlength="12"
                  style="width: 49%;float: right"
                  @input.native="inuptCount(scope, 'mainNum')"
                >
                  <template slot="append">{{ scope.row.mainUnitName }}</template>
                </el-input>
              </span>
              <span v-else-if="item.prop == 'warehouseName'" style="display: flex;justify-content: center;align-items: center">
                <span v-if="scope.$index !== rowIndex">{{ scope.row.warehouseName }}</span>
                <zSelect
                  v-else
                  v-model="scope.row.warehouseId"
                  :show-name="scope.row.warehouseName"
                  class="edit-input"
                  :value.sync="scope.row.warehouseId"
                  url="api/dropDown/basWarehouseList"
                  @change="setProduct($event,scope,'warehouseName')"
                />
              </span>
              <span v-else-if="item.prop == 'storehouseName'">
                <span v-if="scope.$index !== rowIndex">{{ scope.row.storehouseName }}</span>
                <zSelect v-else :value.sync="scope.row.storehouseId" :show-name="scope.row.storehouseName" :params="{warehouseId:scope.row.warehouseId}" url="api/dropDown/basStorehouseList" style="width: 100%;" @change="setProduct($event,scope,'storehouseName')" />
              </span>
              <span v-else-if="item.prop == 'goodsTagName'" style="display: flex;justify-content: center;align-items: center">
                <span v-if="scope.$index !== rowIndex">{{ scope.row.goodsTagName }}</span>
                <zSelect v-else :value.sync="scope.row.goodsTagId" :show-name="scope.row.goodsTagName" :label="scope.row.goodsTagName" url="api/dropDown/basGoodsTagList" style="width: 100%;" @change="setProduct($event,scope,'goodsTagName')" />
              </span>
              <span v-else-if="item.prop == 'remark'">
                <span v-if="scope.$index !== rowIndex">{{ scope.row.remark }}</span>
                <el-input v-else v-model="scope.row.remark" type="textarea" style="width: 100%;" />
              </span>
              <span v-else-if="item.prop == 'usableBoxNum'">
                <span>{{ scope.row.usableBoxNum || 0 }}{{ scope.row.boxUnitName }}</span>
                <span>{{ scope.row.usableMainNum || 0 }}{{ scope.row.mainUnitName }}</span>
              </span>
            </span>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="isSubmit" class="bottom-btnBox flex flex-reverse">
      <el-button type="primary" @click="save">提交</el-button>
    </div>
    <el-dialog
      title="表格配置"
      :visible.sync="tableConfigShow"
      width="60%"
    >
      <j-table-column-config model-name="wareReturnBottleBoxDetail" :columns.sync="header" @tabSave="tabSave" @pit="pit" />
    </el-dialog>
    <div :id="'menu'+typeName" class="menu">
      <div @click="addDetail">新增</div>
      <div @click="delDetail">删除</div>
      <div @click="()=>{menu.style.display = 'none';tableConfig()}">菜单设置</div>
    </div>

    <vue-context-menu
      :context-menu-data="contextMenuData"
      @addDetail="addDetail"
      @delDetail="delDetail"
      @tableConfig="tableConfig"
    />
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="选择商品"
      destroy-on-close
      close-on-press-escape
      :visible.sync="showQueryGoods"
      append-to-body
      width="80vw"
    >
      <j-goods-select v-if="showQueryGoods" :table-name="'table1'+typeName" :no-return-box="false" :customer-id="order.customerId" :type="orderGoodsType" :query-goods="queryGoods" @diaLogGoodsChange="changeGoods" @closeDialog="closeDialog" />
    </el-dialog>
  </div>
</template>

<script>
import { getHeaderProperties } from '@/api/erp/headerProperties'
import headerProperties from '@/api/erp/headerProperties'
import request from '@/utils/request'
import Vue from 'vue'
import { tablemixins } from '@/mixins/tablemixins'
import jTableColumnConfig from '@/components/jTableColumnConfig/jTableColumnConfig'
import jGoodsSelect from '@/components/jGoodsSelect/jGoodsSelect'

export default {
  name: 'JBillDetail',
  components: { jTableColumnConfig, jGoodsSelect },
  mixins: [tablemixins],
  props: {
    url: { type: String },
    type: { type: String },
    headerQuery: { type: Object },
    params: { type: Object },
    update: {
      type: Boolean,
      default: false
    },
    order: {
      type: Object,
      default: null
    },
    orderGoodsType: {
      type: String,
      default: 'SALE'
    },
    addUrl: {
      type: String,
      default: ''
    },
    delUrl: {
      type: String,
      default: ''
    },
    autoList: {
      type: Array,
      default: null
    },
    isSubmit: {
      type: Boolean,
      default: false
    },
    isSelected: {
      type: Boolean,
      default: false
    },
    isAdd: {
      type: Boolean,
      default: false
    },
    typeName: {
      type: String,
      default: ''
    },
    islogistiLoad: {
      type: Boolean,
      default: false
    },
    isEditWithoutReject: {
      type: Boolean,
      default: false
    },
    isIgnoreReturnBoxPass: {
      type: Boolean,
      default: false
    },
    access:{
      type:String,
      default:'content'
    },
    head:{
      type: Array,
      default:()=>[]
    }
  },
  data() {
    return {
      selectedIndex: [],
      list: [],
      selections: [],
      addReturnBillDetail: false,
      header: [],
      queryGoods: {
        keyword: '',
        index: null,
        goodsTagName: '回瓶回箱',
        type: this.orderGoodsType
      },
      crud: {
        headerInfo: { path: null }
      },
      showQueryGoods: false,
      contextMenuData: {
        menuName: 'detailTable',
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [
          {
            fnHandler: 'addDetail', // 绑定事件
            icoName: 'el-icon-plus', // icon图标
            btnName: '添加明细' // 菜单名称
          },
          {
            fnHandler: 'delDetail', // 绑定事件
            icoName: 'el-icon-delete', // icon图标
            btnName: '删除明细' // 菜单名称
          },
          {
            fnHandler: 'tableConfig', // 绑定事件
            icoName: 'el-icon-setting', // icon图标
            btnName: '表格设置' // 菜单名称
          }
        ]
      },
      detailDefault: {},
      loading: false,
      menu: null
    }
  },
  watch: {
    'params': {
      handler(n, o) {
        this.list = []
        if (!this.params.id) return
        this.onGet(this.url, this.type, this.params).then(res => {
          if (res.status === 200) {
            this.list = this.getAccess(res.data,this.access)
            this.auto()
          } else {
            if (res.msg === '回瓶回箱明细对应单据记录不存在,不允许删除') {
              this.list = []
            }
          }
        })
      },
      deep: true
    }
  },
  mounted() {
    window.addEventListener('keydown', this.keyDown)
    this.$refs['table1' + this.typeName].$el.addEventListener('contextmenu', this.showMenu)
    this.$refs['table1' + this.typeName].$el.addEventListener('click', this.clickEve)
  },
  activated() {
    window.addEventListener('keydown', this.keyDown)
  },
  deactivated() {
    window.removeEventListener('keydown', this.keyDown)
  },
  beforeDestroy() {
    window.removeEventListener('keydown', this.keyDown)
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['table1' + this.typeName].doLayout()
    })
  },
  created() {
    if (this.head.length){
      this.header = this.head
    }else {
      getHeaderProperties(this.headerQuery)
        .then(res => {
          this.header = JSON.parse(res.data.header.content)
          for (const key in this.header) {
            this.detailDefault[this.header[key].prop] = null
          }
          this.$forceUpdate()
        })
    }

    if (!this.params.id) return
    this.onGet(this.url, this.type, this.params).then(res => {
      if (res.status === 200) {
        this.list =  this.getAccess(res.data,this.access)
        this.auto()
      } else {
        if (res.msg === '回瓶回箱明细对应单据记录不存在,不允许删除') {
          this.list = []
        }
      }
    })
    this.user = this.$store.state.user.user
    this.crud.headerInfo.path = this.headerQuery.url
  },
  methods: {
    onGet(url, type, params) {
      return request({
        url: url,
        method: type,
        params: params
      })
    },
    getAccess(list,str){
      const pathList = str.split('.')
      let pointer = list
      let i
      while (i=pathList.shift())pointer=pointer[i]
      return pointer
    },
    clickEve(e) {
      if (!e.path.includes(this.menu)) {
        this.menu.style.display = 'none'
      }
    },
    showMenu(e) {
      if (!this.update || !this.order.id || this.isAdd) {
        return
      }
      event.preventDefault()
      this.menu = document.querySelector('#menu' + this.typeName)
      this.menu.style.top = e.clientY + 'px'
      this.menu.style.left = e.clientX + 'px'
      this.menu.style.display = 'block'
      // Get the current location
      // this.contextMenuData.axis = {
      //   x, y
      // }
    },
    columnLabel(obj) {
      if (obj.showName) {
        return obj.showName
      }
      obj.showName = obj.label
      return obj.showName
    },
    addDetail() {
      const { ...newObj } = this.detailDefault
      this.list.push(newObj)
      this.menu.style.display = 'none'
    },
    delDetail() {
      this.menu.style.display = 'none'
      if (this.selectedIndex.length === 0) {
        this.$message.error('请先选择明细行')
        return
      } else if (this.selectedIndex.length > 1) {
        this.$message.error('只能选择一行明细行删除')
        return
      }
      if (this.selections[0].id) {
        const obj = {
          url: this.delUrl,
          method: 'post',
          data: this.selections[0].id
        }
        request(obj).then(res => {
          if (res.status === 200) {
            this.$message.success(res.msg)
            this.list = []
            this.onGet(this.url, this.type, this.params).then(res => {
              if (res.status === 200) {
                this.list =  this.getAccess(res.data,this.access)
                this.auto()
              } else {
                if (res.msg === '回瓶回箱明细对应单据记录不存在,不允许删除') {
                  this.list = []
                }
              }
            })
          } else {
            this.$message.error(res.msg)
          }
        })
      } else {
        this.list.splice(this.selections[0].index, 1)
      }
    },
    closeDialog(val) {
      this.showQueryGoods = false
    },
    formatNum: function(num, n = 6) {
      n = n ? parseInt(n) : 0
      if (n <= 0) {
        return Math.round(num)
      }
      num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n) // 四舍五入
      num = Number(num).toFixed(n) // 补足位数
      return num
    },
    selectRow(row) {
      this.$refs['table1' + this.typeName].toggleRowSelection(row)
    },
    selectionChangeHandler(val) {
      this.selections = val
      this.selectedIndex = val.map(item => item.index)
    },
    computedMoney(row) {
      // 计算价格
      row.noTaxAmount = this.formatNum(row.noTaxBoxPrice * row.boxNum + row.noTaxPrice * row.mainNum)
      row.taxAmount = this.formatNum(row.taxBoxPrice * row.boxNum + row.taxPrice * row.mainNum)
      this.$forceUpdate()
    },
    tabSave() {
      this.tableConfigShow = false
      this.toUpdateHeader()
      this.handleCancelSort()
    },
    auto() {
      if (this.autoList) {
        for (const i in this.autoList) {
          if (this.autoList[i] === 'warehouse') {
            this.detailDefault['warehouseId'] = this.order.warehouseId
            this.detailDefault['warehouseName'] = this.order.warehouseName
          }
        }
      }
    },
    toUpdateHeader() {
      const data = {
        name: this.headerQuery.modelName,
        code: this.headerQuery.modelName,
        path: this.headerQuery.url,
        userId: this.user.userId,
        content: JSON.stringify(this.header)
      }
      headerProperties.add(data).then(res => {
      }).catch(err => {
      })
    },
    switchRowIndex(row) {
      if (row.index === this.rowIndex || !this.isSelected) {
        this.rowIndex = -1
        return
      }
      this.rowIndex = row.index
    },
    inuptCount({ row, $index }, key, type) {
      const list = ['mainNum', 'mainNum', 'boxUnitId', 'goodsCount', 'taxPrice', 'boxNum', 'boxCount', 'productCount', 'totalGrossWeight', 'totalNetWeight', 'detailNum', 'count', 'taxPrice']
      if (row.goodsId) {
        const product_type = row.priceType || ''
        var boxCount = Number(row.goodsCount || 0) / Number(row.boxUnitCount || 0)
        if (key == 'taxPrice') {
          if (product_type == 'SINGLE') {
            row.taxBoxPrice = Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0).toFixed(2)
            row.noTaxPrice = Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(2)
            row.noTaxBoxPrice = Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(2)
            row.taxAmount = Number(row.taxPrice || 0) * Number(row.goodsCount || 0).toFixed(2)
            row.noTaxAmount = Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0).toFixed(2)
            row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0).toFixed(2)
          } else {
            row.taxBoxPrice = Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0).toFixed(2)
            row.noTaxPrice = Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(2)
            row.noTaxBoxPrice = Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(2)
            row.taxAmount = Number(row.taxBoxPrice || 0) * Number(boxCount || 0).toFixed(2)
            row.noTaxAmount = Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0).toFixed(2)
            row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0).toFixed(2)
          }
          // row.discountRate = Number(row.taxPrice || 0) / Number(row.oldTaxPrice || 0) || 0
        }
        if (key == 'taxBoxPrice') {
          if (product_type == 'SINGLE') {
            row.taxPrice = (Number(row.taxBoxPrice || 0) / (Number(row.boxUnitCount || 0))).toFixed(2)
            row.noTaxPrice = (Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(2)
            row.noTaxBoxPrice = (Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(2)
            row.taxAmount = (Number(row.taxPrice || 0) * Number(row.goodsCount || 0)).toFixed(2)
            row.noTaxAmount = (Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0)).toFixed(2)
            row.tax = (Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)).toFixed(2)
            row.discountRate = (Number(row.taxBoxPrice || 0) / Number(row.oldTaxBoxPrice || 0)).toFixed(2)
            row.discountAmount = (Number(row.oldTaxPrice || 0) * Number(row.goodsCount || 0) - Number(row.taxAmount || 0)).toFixed(2)
          } else {
            row.taxPrice = (Number(row.taxBoxPrice || 0) / (Number(row.boxUnitCount || 0))).toFixed(2)
            // row.taxBoxPrice = (Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0)).toFixed(2)
            row.noTaxPrice = (Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(2)
            row.noTaxBoxPrice = (Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(2)
            row.noTaxAmount = (Number(row.noTaxPrice || 0 * boxCount || 0)).toFixed(2)
            row.taxAmount = (Number(row.taxPrice || 0) * Number(row.goodsCount || 0)).toFixed(2)
            row.tax = (Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)).toFixed(2)
          }
        }
        if (key == 'discountRate') {
          row.taxPrice = (Number(row.oldTaxPrice) * (Number(row.discountRate || 0) / 100)).toFixed(2)
          row.taxBoxPrice = (Number(row.oldTaxBoxPrice) * (Number(row.discountRate || 0) / 100)).toFixed(2)
          row.noTaxPrice = (Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(2)
          row.noTaxBoxPrice = (Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0)) / 100).toFixed(2)
          row.taxAmount = (Number(row.taxPrice || 0) * Number(row.goodsCount || 0)).toFixed(2)
          row.noTaxAmount = (Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0)).toFixed(2)
          row.tax = (Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)).toFixed(2)
          row.discountAmount = (Number(row.oldTaxPrice || 0) * Number(row.goodsCount || 0) - Number(row.taxAmount || 0)).toFixed(2)
        }
        if (key == 'mainNum' || key == 'boxNum') {
          row.goodsCount = (Number(row.boxUnitCount * row.boxNum || 0) + Number(row.mainUnitCount * row.mainNum || 0))
          row.boxCount = (Number(row.goodsCount || 0) / Number(row.boxUnitCount || 0)).toFixed(2)
          row.taxAmount = (Number(row.taxPrice || 0) * Number(row.goodsCount || 0)).toFixed(2)
          row.noTaxAmount = (Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0)).toFixed(2)
          row.tax = (Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)).toFixed(2)
          row.discountAmount = (Number(row.oldTaxPrice || 0) * Number(row.goodsCount || 0) - Number(row.taxAmount || 0)).toFixed(2)
        }
        if (key == 'goodsCount') {
          const info = parseInt(Number(row.goodsCount || 0) / Number(row.boxUnitCount || 0))
          row.boxNum = info
          if (row.boxUnitCount * info > row.goodsCount) {
            row.mainNum = (Number(row.boxUnitCount * info) - Number(row.goodsCount || 0))
          } else {
            row.mainNum = (Number(row.goodsCount || 0) - Number(row.boxUnitCount * info))
          }
        }
      } else {
        if (key == 'mainNum') {
          row.mainNum = row[key]
        } else if (key == 'boxNum') {
          row.boxNum = row[key]
        }
        if (key == 'goodsCount') {
          row.mainNum = ''
          row.boxNum = ''
        }
      }
      row.discountRate = (row.taxPrice / row.oldTaxPrice).toFixed(2) * 100
      this.$set(this.list, $index, row)
    },
    setProduct(event, { row, $index }, name) {
      const table = this.list
      if (event) {
        if (name == 'warehouseName') {
          row.warehouseName = event.name
          row.storehouseId = ''
          row.storehouseName = ''
          row.warehouseId = event.id
        }
        if (name == 'storehouseName') {
          row.storehouseName = event.name
          row.storehouseId = event.id
        }
        if (name == 'goodsTagName') {
          row.goodsTagName = event.name
          row.goodsTagId = event.id
        }

        Vue.set(table, $index, row)
      }
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    changeGoods(val) {
      this.showQueryGoods = false
      this.diaLogGoodsChange(val)
      this.$refs['table1' + this.typeName].setCurrentRow(this.list[this.rowIndex])
    },
    rowClass({ row, rowIndex }) {
      if (this.selectedIndex.indexOf(rowIndex) >= 0) {
        return {
          'border': 'solid 1px #3dffef',
          'background-color': '#fafc7e',
          'height': '10px'
        }
      } else {
        return {
          'height': '10px'
        }
      }
    },
    diaLogGoodsChange({ row, index, data }) {
      const table = this.list
      const href = window.location.href
      row.goodsName = data.goodsName
      row.goodsCode = data.goodsCode
      row.goodsId = parseInt(data.goodsId)
      row.barcode = data.barcode
      row.boxUnitId = data.boxUnitId
      row.boxUnitName = data.boxUnitName
      row.boxUnitCount = data.boxUnitCount
      row.boxUnitId = data.boxUnitId
      row.boxNum = data.boxNum
      row.mainNum = data.mainNum
      row.mainUnitName = data.mainUnitName
      row.mainUnitId = data.mainUnitId
      row.mainUnitCount = data.mainUnitCount
      row.mainUnitCode = data.mainUnitCode
      row.boxBarcode = data.boxBarcode
      row.batchNo = data.batchNo
      row.discountAmount = data.discountAmount
      row.discountRate = data.discountRate
      row.createTime = data.createTime
      row.createUserCode = data.createUserCode
      row.createUserId = data.createUserId
      row.createUserName = data.createUserName
      row.cutOffGoodsCount = data.cutOffGoodsCount
      row.effectGoodsCount = data.effectGoodsCount
      row.firstUnitCode = data.firstUnitCode
      row.firstUnitCount = data.firstUnitCount
      row.firstUnitId = data.firstUnitId
      row.firstUnitName = data.firstUnitName
      row.goodsBrandCode = data.goodsBrandCode
      row.goodsBrandId = data.goodsBrandId
      row.goodsBrandName = data.goodsBrandName
      row.goodsTagCode = data.goodsTagCode
      row.goodsTagId = data.goodsTagId
      row.goodsTypeCode = data.goodsTypeCode
      row.goodsTagName = data.goodsTagName
      row.goodsTypeId = data.goodsTypeId
      row.goodsTypeName = data.goodsTypeName
      row.helpSign = data.helpSign
      row.model = data.model
      row.seq = data.seq
      row.pickGoodsCount = data.pickGoodsCount
      row.orderCode = data.orderCode
      row.orderId = data.orderId
      row.remark = data.remark
      row.taxCode = data.taxCode
      row.taxId = data.taxId
      row.taxName = data.taxName
      row.taxRate = data.taxRate || 0
      row.updateTime = data.updateTime
      row.updateUserCode = data.updateUserCode
      row.updateUserId = data.updateUserId
      row.updateUserName = data.updateUserName
      row.effectGoodsCount = data.effectGoodsCount
      row.firstUnitCode = data.firstUnitCode
      row.firstUnitCount = data.firstUnitCount
      row.firstUnitId = data.firstUnitId
      row.firstUnitName = data.firstUnitName
      row.secondUnitCode = data.secondUnitCode
      row.secondUnitCount = data.secondUnitCount
      row.secondUnitId = data.secondUnitId
      row.secondUnitName = data.secondUnitName
      row.priceType = data.priceType
      row.boxCount = data.boxCount
      row.thirdUnitCode = data.thirdUnitCode
      row.thirdUnitCount = data.thirdUnitCount
      row.thirdUnitId = data.thirdUnitId
      row.thirdUnitName = data.thirdUnitName

      row.fourthUnitCode = data.fourthUnitCode
      row.fourthUnitCount = data.fourthUnitCount
      row.fourthUnitId = data.fourthUnitId
      row.fourthUnitName = data.fourthUnitName

      row.minSaleUnitCode = data.minSaleUnitCode
      row.minSaleUnitCount = data.minSaleUnitCount
      row.minSaleUnitId = data.minSaleUnitId
      row.minSaleUnitName = data.minSaleUnitName

      row.minReturnUnitCode = data.minReturnUnitCode
      row.minReturnUnitCount = data.minReturnUnitCount
      row.minReturnUnitId = data.minReturnUnitId
      row.minReturnUnitName = data.minReturnUnitName
      row.discountRate = data.discountRate
      row.storehouseName = data.storehouseName
      row.warehouseName = this.detailDefault.warehouseName || data.warehouseName
      row.storehouseId = data.storehouseId
      row.warehouseId = this.detailDefault.warehouseId || data.warehouseId
      row.boxCount = data.boxCount
      row.discountRate = data.discountRate
      row.promotionType = data.promotionType
      row.outStorehouseName = data.outStorehouseName
      row.inStorehouseName = data.inStorehouseName
      row.outProducedDate = data.outProducedDate
      row.outDeadlineDate = data.outDeadlineDate
      row.inProducedDate = data.inProducedDate
      row.inDeadlineDate = data.inDeadlineDate
      row.occupyNum = data.occupyNum
      row.occupyBox = data.occupyBox
      row.existNum = data.existNum
      row.existBox = data.existBox
      row.existMainNum = data.existMainNum
      row.paperNum = data.paperNum
      row.paperBoxNum = data.paperBoxNum
      row.paperMainNum = data.paperMainNum
      row.goodsCount = data.goodsCount
      row.boxCount = data.boxCount
      row.oldGoodsCount = data.goodsCount
      row.oldMainNum = data.mainNum
      row.oldBoxNum = data.boxNum

      row.profitLossBox = data.profitLossBox
      row.profitLossNum = data.profitLossNum
      row.profitLossMainNum = data.profitLossMainNum
      row.deadlineDate = data.deadlineDate
      row.producedDate = data.producedDate
      row.boxCount = data.boxCount
      row.oldMainNum = data.oldMainNum

      row.oldBoxNum = data.oldBoxNum
      row.weight = data.weight
      row.volume = data.volume
      row.packageType = data.packageType

      row.isPromotion = data.isPromotion
      row.effectGoodsCount = data.effectGoodsCount
      row.cutOffGoodsCount = data.cutOffGoodsCount
      row.boxTaxPrice = data.boxTaxPrice
      row.boxNoTaxPrice = data.boxNoTaxPrice
      row.sourceCode = data.sourceCode

      row.sourceDetailType = data.sourceDetailType
      row.promotionId = data.promotionId
      row.promotionCode = data.promotionCode
      row.promotionName = data.promotionName
      row.promotionType = data.promotionType
      row.promotionStartDate = data.promotionStartDate
      row.promotionEndDate = data.promotionEndDate
      row.promotionTaxPrice = data.promotionTaxPrice
      row.promotionTaxBoxPrice = data.promotionTaxBoxPrice
      row.effectGoodsCount = data.effectGoodsCount
      row.cutOffGoodsCount = data.cutOffGoodsCount
      row.saleTaxPrice = data.saleTaxPrice
      row.outLocationId = data.outLocationId
      row.outLocationCode = data.outLocationCode
      row.outLocationName = data.outLocationName
      row.inLocationId = data.inLocationId
      row.inLocationCode = data.inLocationCode
      row.inLocationName = data.inLocationName

      row.outStorehouseCode = data.outStorehouseCode
      row.outStorehouseId = data.outStorehouseId
      row.outStorehouseName = data.outStorehouseName
      row.inStorehouseName = data.inStorehouseName
      row.inStorehouseCode = data.inStorehouseCode
      row.inStorehouseId = data.inStorehouseId
      row.boxUnitId = data.boxUnitId
      row.boxUnitName = data.boxUnitName
      row.usableNum = data.usableNum
      row.usableBoxNum = data.usableBoxNum
      row.usableMainNum = data.usableMainNum
      // const boxCount = parseInt(Number(data.usableNum)/Number(data.boxUnitCount))
      // const mainCount = data.usableNum%Number(data.boxUnitCount)
      // row.usableBoxNum = `${boxCount}${data.boxUnitName}${mainCount}${data.mainUnitName}`

      if (row.isPromotion == 1 && row.promotionType == 1) {
        if (row.goodsCount <= row.cutOffGoodsCount && row.goodsCount >= row.effectGoodsCount) {
          row.noTaxPrice = data.promotionNoTaxPrice
          row.taxPrice = data.promotionTaxPrice
          row.oldTaxPrice = data.promotionTaxPrice
          row.oldTaxBoxPrice = data.promotionTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.taxBoxPrice = data.promotionTaxBoxPrice
          row.remark = data.promotionRemark
        } else if (row.cutOffGoodsCount == 0) {
          row.taxPrice = data.promotionTaxPrice
          row.noTaxPrice = data.promotionNoTaxPrice
          row.taxPrice = data.promotionTaxPrice
          row.oldTaxPrice = data.promotionTaxPrice
          row.oldTaxBoxPrice = data.promotionTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.taxBoxPrice = data.promotionTaxBoxPrice
          row.remark = data.promotionRemark
        } else if (row.cutOffGoodsCount > 0 && row.goodsCount <= row.cutOffGoodsCount) {
          row.taxPrice = data.promotionTaxPrice
          row.noTaxPrice = data.promotionNoTaxPrice
          row.taxPrice = data.promotionTaxPrice
          row.oldTaxPrice = data.promotionTaxPrice
          row.oldTaxBoxPrice = data.promotionTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.taxBoxPrice = data.promotionTaxBoxPrice
          row.remark = data.promotionRemark
        } else {
          row.taxPrice = data.taxPrice
          row.noTaxPrice = data.noTaxPrice
          row.taxPrice = data.taxPrice
          row.oldTaxPrice = data.taxPrice
          row.oldTaxBoxPrice = data.taxBoxPrice
          row.noTaxBoxPrice = data.noTaxBoxPrice
          row.noTaxBoxPrice = data.noTaxBoxPrice
          row.taxBoxPrice = data.taxBoxPrice
          row.taxBoxPrice = data.taxBoxPrice
        }
      } else {
        row.taxPrice = data.taxPrice
        row.noTaxPrice = data.noTaxPrice
        row.taxPrice = data.taxPrice
        row.oldTaxPrice = data.taxPrice
        row.oldTaxBoxPrice = data.taxBoxPrice
        row.noTaxBoxPrice = data.noTaxBoxPrice
        row.noTaxBoxPrice = data.noTaxBoxPrice
        row.taxBoxPrice = data.taxBoxPrice
        row.taxBoxPrice = data.taxBoxPrice
      }

      Vue.set(table, index, row)
      // const rows = {
      //   isSelected: true,
      //   warehouseId: row.warehouseId,
      //   warehouseName: row.warehouseName,
      //   taxAmount: row.taxAmount,
      //   bomCount: row.bomCount,
      //   existNum: row.existNum,
      //   occupyNum: row.occupyNum
      // }
      // Vue.set(table, index, rows)
    },
    keyDown() {
      try {
        if (this.showAddBatchDialog || this.showQueryGoods) {
          return
        }
        if (event.keyCode === 121) {
          if (this.order.orderStatus !== 'PASS') {
            event.preventDefault()
            this.toAddList()
          }
        }
        const elTable = this.$refs['table1' + this.typeName].$el
        if (!elTable) { return }
        const row = this.$refs['table1' + this.typeName].store.states.currentRow
        let index, cells
        const list = []
        if (row !== null) {
          index = row.index
          cells = elTable.querySelectorAll('.el-table__body tr')[index].querySelectorAll('.el-input__inner,.el-textarea__inner')
          cells.forEach(item => {
            if (item.placeholder != '请输入内容搜索') {
              list.push(item)
            }
          })
        } else {
          index = -1
          cells = elTable.querySelectorAll('.el-table__body tr')[0].querySelectorAll('.el-input__inner,.el-textarea__inner')
        }

        if (list[this.columnIndex] !== document.activeElement) {
          for (let i = 0; i < list.length; i++) {
            if (list[i] === document.activeElement) {
              this.columnIndex = i
              break
            }
          }
        }
        if (this.order.orderStatus !== 'PASS') {
          if (event.keyCode === 39) {
            if (this.columnIndex < list.length - 1) {
              this.columnIndex++
            }
            list[this.columnIndex].focus()
            setTimeout(() => { list[this.columnIndex].select() }, 10)
          } else if (event.keyCode === 40) {
            if (this.list[index + 1] === undefined) {
              new Promise((resolve, reject) => {
                this.addDetail()
                this.$refs['table1' + this.typeName].setCurrentRow(this.list[index + 1])
                this.$forceUpdate()
                resolve('yes')
              }).then(() => {
                this.rowIndex = index + 1
                setTimeout(() => {
                  cells = elTable.querySelectorAll('.el-table__body tr')[this.rowIndex].querySelectorAll('.el-input__inner,.el-textarea__inner')
                  const list = []
                  cells.forEach(item => {
                    if (item.placeholder != '请输入内容搜索') {
                      list.push(item)
                    }
                  })
                  list[0].focus()
                  setTimeout(() => { list[0].select() }, 10)
                  this.columnIndex = 0
                }, 200)
              })
            } else {
              this.rowIndex = index + 1
              this.$refs['table1' + this.typeName].setCurrentRow(this.list[this.rowIndex])
              setTimeout(() => {
                cells = elTable.querySelectorAll('.el-table__body tr')[this.rowIndex].querySelectorAll('.el-input__inner,.el-textarea__inner')
                const list = []
                cells.forEach(item => {
                  if (item.placeholder != '请输入内容搜索') {
                    list.push(item)
                  }
                })
                list[this.columnIndex].focus()
                setTimeout(() => { list[this.columnIndex].select() }, 10)
              }, 200)
            }
          } else if (event.keyCode === 38) {
            if (index > 0) {
              this.rowIndex = index - 1
              this.$refs['table1' + this.typeName].setCurrentRow(this.list[this.rowIndex])
              setTimeout(() => {
                cells = elTable.querySelectorAll('.el-table__body tr')[this.rowIndex].querySelectorAll('.el-input__inner,.el-textarea__inner')
                const list = []
                cells.forEach(item => {
                  if (item.placeholder != '请输入内容搜索') {
                    list.push(item)
                  }
                })

                list[this.columnIndex].focus()
                setTimeout(() => { list[this.columnIndex].select() }, 10)
              }, 200)
            }
          } else if (event.keyCode === 37) {
            if (this.columnIndex > 0) {
              this.columnIndex--
            }
            list[this.columnIndex].focus()
            setTimeout(() => { list[this.columnIndex].select() }, 10)
          } else if (event.keyCode === 13) {
            if (list[this.columnIndex] == document.activeElement) {
              if (list[this.columnIndex].placeholder === '请输入商品') {
                // this.queryGoods = {keyword:list[this.columnIndex].value,index:this.rowIndex}
                this.queryGoods['keyword'] = list[this.columnIndex].value
                this.queryGoods['index'] = this.rowIndex
                this.showQueryGoods = true
              } else {
                list[this.columnIndex].blur()
              }
            } else {
              list[this.columnIndex].focus()
            }
          }
        }

        if (event.keyCode === 122) {
          event.preventDefault()
          event.returnValue = !event.returnValue
          this.showPriceDetail(row)
        }
      } catch (e) {
        console.log(e)
      }
    },
    changeColWidth(nw, ow, col, evt) {
      const list = this.header
      list.map((res, i) => {
        if (res.showName === col.label) {
          this.header[i].width = nw
        }
      })
      this.toUpdateHeader()
    },
    save() {
      this.loading = true
      const ids = []
      this.list.forEach((item, index) => {
        if (!item.goodsId) {
          ids.push(index)
        }
      })
      for (let i = ids.length - 1; i >= 0; i--) {
        this.list.splice(ids[i], 1)
      }
      this.order.sourceCode = null
      this.order.sourceId = null
      this.order.sourceType = null
      const data = { ...this.order, detailList: this.list }
      data.id = this.params.id
      if (this.isEditWithoutReject) { data.isEditWithoutReject = 1 }
      if (this.isIgnoreReturnBoxPass) { data.isIgnoreReturnBoxPass = 1 }
      const obj = {
        url: this.addUrl,
        method: 'post',
        data
      }
      request(obj).then(res => {
        if (res.status === 200) {
          this.$message.success(res.msg)
          this.onGet(this.url, this.type, this.params).then(res => {
            this.list =  this.getAccess(res.data,this.access)
            this.auto()
          })
          this.loading = false
          this.$emit('parenUpdate', '1')
        } else {
          this.$message.error(res.msg)
          this.loading = false
        }
      }).catch(err => { this.loading = false })
    }
  }
}
</script>

<style scoped>
.bottom-btnBox{
  padding: 20px;
}
.menu{
  position: fixed;
  display: none;
  background-color: #ffffff;
  border: rgb(203,203,2030) 1px solid;
}
.menu>div{
  width: 200px;
  height: 40px;
  display: flex;
  align-items: center;
  z-index: 9999;
  cursor: pointer;
  font-size: 20px;
}
.menu>div:hover{
  background-color: blue;
}
</style>
